// 背景动效入口文件
// 注意：移除ES6模块语法，使用普通JavaScript方式

// 确保所有动效模块已加载
(function() {
    // 动态加载所有动效模块
    const effectModules = [
        '/static/js/background-effects/gradient.js',
        '/static/js/background-effects/particles.js',
        '/static/js/background-effects/circles.js',
        '/static/js/background-effects/snow.js',
        '/static/js/background-effects/custom-image.js',
        '/static/js/background-effects/starry-sky.js'
    ];
    
    let loadedCount = 0;
    
    effectModules.forEach(module => {
        const script = document.createElement('script');
        script.src = module;
        script.onload = function() {
            loadedCount++;
            console.log(`Loaded module: ${module}, ${loadedCount}/${effectModules.length}`);
            if (loadedCount === effectModules.length) {
                console.log('All background effect modules loaded');
                // 当所有模块加载完成后，优先使用pendingEffectType，其次使用window.backgroundEffect
                const effectToInit = window.getPendingEffectType ? window.getPendingEffectType() : window.backgroundEffect;
                if (effectToInit && typeof window.initBackgroundEffect === 'function') {
                    console.log('Re-initializing background effect after all modules loaded:', effectToInit);
                    // 直接使用已定义的initBackgroundEffect函数，不需要重新定义
                    // 确保canvas元素存在
                    const canvas = document.getElementById('background-canvas');
                    if (canvas) {
                        // 直接调用全局的initBackgroundEffect函数，它现在应该已经被正确覆盖
                        // initBackgroundEffect内部会处理canvas尺寸设置
                        window.initBackgroundEffect(effectToInit);
                    } else {
                        console.error('Background canvas not found');
                    }
                }
            }
        };
        script.onerror = function() {
            console.error(`Failed to load module: ${module}`);
        };
        document.head.appendChild(script);
    });
})();

// 定义有效的动效类型列表（已移除stars）
const validEffects = [
    'none', 'snow', 'particles', 
    'circles', 'gradient', 'starry-sky', 
    'custom-image'
];

// 存储当前活跃的背景效果清理函数
let activeEffectCleanup = null;

// 主初始化函数
function initBackgroundEffect(effectType = 'gradient') {
    console.log('Initializing background effect:', effectType);
    
    // 清理之前的效果
    if (activeEffectCleanup && typeof activeEffectCleanup === 'function') {
        console.log('Cleaning up previous background effect');
        activeEffectCleanup();
        activeEffectCleanup = null;
    }
    
    // 爱情视频功能已移除
    
    // 获取或创建canvas元素
    let canvas = document.getElementById('background-canvas');
    if (!canvas) {
        const container = document.getElementById('background-container');
        if (container) {
            canvas = document.createElement('canvas');
            canvas.id = 'background-canvas';
            container.appendChild(canvas);
        } else {
            console.error('Background container not found');
            return;
        }
    }
    
    // 确保背景容器和canvas有正确的样式设置
    const container = document.getElementById('background-container');
    if (container) {
        container.style.position = 'absolute';
        container.style.top = '0';
        container.style.left = '0';
        container.style.width = '100%';
        container.style.height = '100%';
    }
    
    // 设置canvas样式为全屏
    canvas.style.position = 'absolute';
    canvas.style.top = '0';
    canvas.style.left = '0';
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.style.display = 'block';
    
    // 清空canvas
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 设置canvas大小
    function resizeCanvas() {
        // 使用window.innerWidth和window.innerHeight确保canvas能铺满整个屏幕
        if (canvas) {
            // 设置canvas的实际绘图尺寸
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            
            // 确保CSS尺寸也正确设置
            canvas.style.width = window.innerWidth + 'px';
            canvas.style.height = window.innerHeight + 'px';
        }
    }
    
    // 初始调整大小
    resizeCanvas();
    
    // 监听窗口大小变化
    if (!window.backgroundResizeListener) {
        window.backgroundResizeListener = resizeCanvas;
        window.addEventListener('resize', resizeCanvas);
    }
    
    // 验证动效类型
    if (!validEffects.includes(effectType)) {
        console.warn(`Invalid effect type: ${effectType}, falling back to gradient`);
        effectType = 'gradient';
    }
    
    // 根据动效类型调用相应的初始化函数
    switch (effectType) {
        case 'none':
            // 清除所有动效
            clearCanvas();
            activeEffectCleanup = null;
            break;
        case 'gradient':
            // 使用全局window对象确保能访问到动态加载的函数
            if (window.initGradientEffect && typeof window.initGradientEffect === 'function') {
                const cleanup = window.initGradientEffect(canvas);
                activeEffectCleanup = cleanup || (() => console.log('Gradient effect cleanup'));
            } else {
                console.warn('渐变效果模块尚未加载，使用默认背景');
                // 使用简单的灰色背景作为回退
                const ctx = canvas.getContext('2d');
                ctx.fillStyle = '#f8f9fa';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
            }
            break;
        case 'particles':
            if (typeof initParticlesEffect === 'function') {
                const cleanup = initParticlesEffect(canvas);
                activeEffectCleanup = cleanup || (() => console.log('Particles effect cleanup'));
            } else {
                console.error('initParticlesEffect not available');
            }
            break;

        case 'circles':
            if (typeof initCirclesEffect === 'function') {
                const cleanup = initCirclesEffect(canvas);
                activeEffectCleanup = cleanup || (() => console.log('Circles effect cleanup'));
            } else {
                console.error('initCirclesEffect not available');
            }
            break;
        case 'snow':
            if (typeof initSnowEffect === 'function') {
                // 配置雪花动效，默认使用纯色背景
                const snowOptions = {
                    backgroundType: 'solid',
                    solidColor: '#8c8cdcff' // 浅蓝色背景
                };
                const cleanup = initSnowEffect(canvas, snowOptions);
                activeEffectCleanup = cleanup || (() => console.log('Snow effect cleanup'));
            } else {
                console.error('initSnowEffect not available');
            }
            break;
        case 'starry-sky':
            if (typeof initStarrySkyEffect === 'function') {
                  const starrySkyOptions = {
                     starCount: 8000, // 优化星星数量
                     rotationSpeed: 0.05, // 优化旋转速度
                     backgroundColor: 'rgba(10, 10, 42, 1)', // 深蓝色背景
                     galaxyEnabled: true,
                     meteorFrequency: 45,
                     twinkleEnabled: true,
                     starSizeRange: { min: 0.3, max: 1.5 }
                  };
                  cleanupFunction = initStarrySkyEffect(canvas, starrySkyOptions);
                activeEffectCleanup = cleanupFunction || (() => console.log('Starry sky effect cleanup'));
            } else {
                console.error('initStarrySkyEffect not available');
            }
            break;


        case 'custom-image':
            if (typeof initCustomImageEffect === 'function') {
                // 传递backgroundImageUrl参数
                const cleanup = initCustomImageEffect(canvas, window.backgroundImageUrl);
                activeEffectCleanup = cleanup || (() => console.log('Custom image effect cleanup'));
            } else {
                console.error('initCustomImageEffect not available');
            }
            break;

        default:
            console.warn(`Unhandled effect type: ${effectType}`);
            break;
    }
}

// 清除canvas内容
function clearCanvas() {
    const canvas = document.getElementById('background-canvas');
    if (canvas && canvas.getContext) {
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
}